package com.liu.shiro.realm;

import com.liu.shiro.entity.Permission;
import com.liu.shiro.entity.Role;
import com.liu.shiro.entity.User;
import com.liu.shiro.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /**
     * 角色认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("认证 ==========》 doGetAuthenticationInfo");
        String username = (String)token.getPrincipal();
        User user = userService.findAllUserInfoByUsername(username);
        String pwd = user.getPassword();
        if (pwd == null || "".equals(pwd)){
            return null;
        }
        return new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(),this.getClass().getName());
    }

    /**
     * 权限校验
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("授权 ==========》 doGetAuthorizationInfo");
        String username = (String)principals.getPrimaryPrincipal();
        User user = userService.findAllUserInfoByUsername(username);

        List<String> StringRoleList = new ArrayList<>();
        List<String> StringPermissionList = new ArrayList<>();

        List<Role> roleList = user.getRoleList();
        for (Role role : roleList) {
            StringRoleList.add(role.getName());

            List<Permission> permissionList = role.getPermissionList();
            for (Permission permission : permissionList) {
                if (permission!=null){
                    StringPermissionList.add(permission.getName());
                }
            }
        }

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(StringRoleList);
        simpleAuthorizationInfo.addStringPermissions(StringPermissionList);

        return simpleAuthorizationInfo;
    }

}
